package client

import (
	"encoding/json"
	"fmt"
	"gin-epg/internal/app/client/utils"
	"gin-epg/internal/app/common/util"
	"gin-epg/internal/app/dao"
	"net/url"
	"time"

	"github.com/go-resty/resty/v2"
	"github.com/spf13/cast"
)

// 所有频道url curl --location --globoff 'http://ottlnyd-cosepg.yys.mgtv.com:8084/ysten-epg/epg/findAssortChannelList.shtml?abilityString={%22abilities%22%3A[]%2C%22businessGroupIds%22%3A[]%2C%22deviceGroupIds%22%3A[%223815%22]%2C%22districtCode%22%3A%22210200%22%2C%22userGroupIds%22%3A[]%2C%22userLabelIds%22%3A[]}'
// 地方id没有
// 易视腾辽宁
var mapYstenLiaoning = map[string]string{
	"H265-3500k-1080P-lnty":   "辽宁体育休闲",
	"H265-3500k-1080P-lnds":   "辽宁都市",
	"H265-3500k-1080P-lnysj":  "辽宁影视剧",
	"H265-3500k-1080P-lnsh":   "辽宁生活",
	"H265-3500k-1080P-lnjyqs": "辽宁教育青少",
	"H265-3500k-1080P-lnbf":   "辽宁北方",
	"H265-3500k-1080P-lngg":   "辽宁公共",
	"H265-3500k-1080P-lnjj":   "辽宁经济",
	"H265-3500k-1080P-lnydds": "辽宁移动电视",
	"H265-3500k-1080P-lnyjgw": "宜佳购物",
	"xindongman":              "新动漫",
	"jiatinglicai":            "家庭理财",
	"youmankaton":             "优漫卡通",
	"jiajiakaton":             "嘉佳卡通",
	// 更多键值对...
}

// HandleYstenLiaoningCron 处理易视腾辽宁节目单
func HandleYstenLiaoningCron() error {
	dao.Logger.Infof("HandleYstenLiaoningCron start")
	date := time.Now().Format("20060102")
	dao.Logger.Infof(date)
	source := "ystenliaoning"

	client := resty.New()
	for key, value := range mapYstenLiaoning {
		dao.Logger.Infof("Key: %s, Value: %s", key, value)
		// 构建URL参数
		params := url.Values{}
		params.Add("uuid", key)
		params.Add("abilityString", `{"abilities":[],"businessGroupIds":[],"deviceGroupIds":["3815"],"districtCode":"210200","userGroupIds":[],"userLabelIds":[]}`)
		params.Add("days", "1")
		// 编码参数
		encodedParams := params.Encode()

		// 构建完整URL
		url := fmt.Sprintf("http://ottlnyd-cosepg.yys.mgtv.com:8084/ysten-epg/epg/findPlaybills.shtml?%s", encodedParams)

		proxyURL, err := util.GetConfigValue("proxy.proxyApiUrlYstenliaoning")
		if err != nil {
			dao.Logger.Errorf("Error: %v", err)
		} else {
			dao.Logger.Infof("proxyApiUrlYstenliaoning: %v", proxyURL)
			url = fmt.Sprintf("%s%s", proxyURL, url[len("http://ottlnyd-cosepg.yys.mgtv.com:8084"):])
		}

		resp, err := client.R().
			SetHeaders(map[string]string{
				"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
			}).
			Get(url)

		if err != nil {
			return fmt.Errorf("failed to get data from URL: %v", err)
		}

		var data map[string]interface{}
		if err := json.Unmarshal(resp.Body(), &data); err != nil {
			return fmt.Errorf("failed to unmarshal JSON: %v", err)
		}

		if resultCode, ok := data["resultCode"].(string); ok && resultCode == "000" {
			if content, ok := data["content"].([]interface{}); ok {
				for _, day := range content {
					dayMap := day.(map[string]interface{})
					//playDate := cast.ToInt64(dayMap["playDate"])
					//dateParsed := time.Unix(playDate, 0).Format("2006-01-02")

					if programs, ok := dayMap["programs"].([]interface{}); ok {
						for _, program := range programs {
							programMap := program.(map[string]interface{})
							startTime := cast.ToInt64(programMap["startTime"])
							endTime := cast.ToInt64(programMap["endTime"])
							momentStartDate := time.Unix(startTime, 0)
							momentStopDate := time.Unix(endTime, 0)

							title := cast.ToString(programMap["programName"])
							desc := ""

							db := dao.SqlSession
							utils.HandleCrossDayRecord(db, momentStartDate, momentStopDate, title, desc, value, source)
						}
					}
				}
			}
		}
	}
	return nil
}
